package com.yang.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmaill.common.dto.PageDTO;
import com.hmaill.fegin.ItemClient;
import com.hmaill.pojo.Item;
import com.yang.dto.ItemDto;
import com.yang.dto.RequestParams;
import com.yang.mapper.TbItemMapper;
import com.yang.service.TbItemService;

import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lo
 */
@Service
@Slf4j
public class TbItemServiceImpl extends ServiceImpl<TbItemMapper, Item> implements TbItemService {


    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ItemClient itemClient;

    /**
     * 分页查询数据
     * @param requestParams
     * @return
     */
    @Override
    public PageDTO<ItemDto> getItem(RequestParams requestParams) {
        try {
            //1.准备request
            SearchRequest request = new SearchRequest("item");

            //添加查询条件
            buildBasicQuery(requestParams, request);

            //2.2分页
            int page = requestParams.getPage();
            int size = requestParams.getSize();
            request.source().from((page - 1) * size).size(size);
            //2.3 排序
            if (!"default".equals(requestParams.getSortBy())) {
                request.source().sort(requestParams.getSortBy(), SortOrder.DESC);
            }

            //2.4 高亮
            request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));

            //3.发出请求
            SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            //4.返回结果解析
            return handleResponse(search);
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    /**
     * 判断参数 添加查询条件
     *
     * @param requestParams
     * @param request
     */
    private void buildBasicQuery(RequestParams requestParams, SearchRequest request) {
        /**
         * 这部分为bool查询 ,属于算分函数的query部分
         */
        // 1.构建BooleanQuery 布尔查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //2.
        // 关键词 key 的全文检索查询
        String key = requestParams.getKey();
        if (Strings.isNotBlank(key)) {
            //非空
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));
        } else {
            //空
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }

        //过滤条件
        //2.1品牌 brand 搜索
        String brand = requestParams.getBrand();
        if (Strings.isNotBlank(brand)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", brand));
        }

        //2.2分类过滤
        String category = requestParams.getCategory();
        if (Strings.isNotBlank(category)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category", category));
        }
        //2.3 价格过滤
        Integer minPrice = requestParams.getMinPrice();
        Integer maxPrice = requestParams.getMaxPrice();
        if (!(minPrice == null && maxPrice == null)) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(minPrice*100).lt(maxPrice*100));
        }

        //放入source
        request.source().query(boolQueryBuilder);
    }

    /**
     * 解析list查询结果
     * @param search
     * @return
     */
    private PageDTO<ItemDto> handleResponse(SearchResponse search) {
        //4.解析响应
        SearchHits searchHits = search.getHits();
        //4.1获取总条数
        long total = searchHits.getTotalHits().value;
        //4.2文档数组
        SearchHit[] hits = searchHits.getHits();
        ArrayList<ItemDto> itemDtoArrayList = new ArrayList<>();
        //4.3遍历数组
        for (SearchHit hit : hits) {
            String string = hit.getSourceAsString();
            ItemDto itemDto = JSON.parseObject(string, ItemDto.class);
            //获取高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (highlightFields != null) {
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField != null) {
                    // 获取高亮值
                    String name = highlightField.getFragments()[0].string();
                    // 覆盖非高亮结果
                    itemDto.setName(name);
                }
            }
            itemDtoArrayList.add(itemDto);
        }
        return new PageDTO<ItemDto>(total, itemDtoArrayList);
    }

    /**
     * 自动补全功能
     * @param key
     * @return
     */
    @Override
    public List<String> getSuggestions(String key) {
        try {
            //1.准备Request
            SearchRequest request = new SearchRequest("item");
            //2.请求参数
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "mySuggestion", SuggestBuilders.completionSuggestion("suggestion")
                            //根据关键词查询
                            .prefix(key)
                            //去重
                            .skipDuplicates(true)
                            //每次返回10条
                            .size(10)
            ));

            //3.发送请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

            //4.返回参数解析
            Suggest suggest = response.getSuggest();
            //4,1 根据名称获取补全结果
            CompletionSuggestion mySuggestion = suggest.getSuggestion("mySuggestion");
            //4.2 创建集合用于存储数据
            ArrayList<String> list = new ArrayList<>();
            //4.3 获取option 并且遍历加入list
            for (CompletionSuggestion.Entry.Option option : mySuggestion.getOptions()) {
                list.add(option.getText().toString());
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 桶聚合
     * @param requestParams
     * @return
     */
    @Override
    public Map<String, List<String>> buckets(RequestParams requestParams) {
        Map<String, List<String>> map = null;
        List<String> category = null;
        List<String> brand = null;
        try {
            //1.准备Request
            SearchRequest request = new SearchRequest("item");

            //2.,准备DSL
            //2.1query
            // 添加查询条件
            buildBasicQuery(requestParams,request);
            //3.  "size": 0, 设置size为0，结果中不包含文档数据，只包含聚合结果
            request.source().size(0);
            //4. 聚合
            //4.1 分类聚合
            String categoryAggName = "category";
            request.source().aggregation(AggregationBuilders.terms(categoryAggName).field("category").size(20));

            //4.2 品牌聚合
            String brandAggName = "brandAggs";
            request.source().aggregation(AggregationBuilders.terms(brandAggName).field("brand").size(20));

            //5. 发送请求
            SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);

            //6. 结果解析
            map = new HashMap<>();
            category = getAggByName(search, categoryAggName);
            brand = getAggByName(search, brandAggName);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //7. 封装返回
        map.put("category",category);
        map.put("brand",brand);
        return map;
    }

    /**
     * 分桶结果解析
     * @param search 返回结果
     * @param name 传递聚合的名称
     * @return
     */
    private List<String> getAggByName(SearchResponse search, String name) {

        Terms aggregation = search.getAggregations().get(name);
        List<? extends Terms.Bucket> buckets = aggregation.getBuckets();

        //将结果存入list集合
        List<String> list = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String bucketKeyAsString = bucket.getKeyAsString();
            list.add(bucketKeyAsString);
        }
        return list;
    }

    /**
     * 更新,添加文档数据
     * 执行一次是增加,
     *执行第二次是修改
     * @param id
     */
    @Override
    public void upDataItemDoc(Long id) {
        try {
            // 1.查询数据库item数据
            Item item = itemClient.searchItem(id);
            // 2.转换为ItemDoc
            ItemDto itemDto = new ItemDto(item);
            // 3.转JSON
            String json = JSON.toJSONString(itemDto);

            // 1.准备Request
            IndexRequest request = new IndexRequest("item").id(itemDto.getId().toString());
            // 2.准备请求参数DSL，其实就是文档的JSON字符串
            request.source(json, XContentType.JSON);
            // 3.发送请求
            restHighLevelClient.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    /**
     * 删除文档数据
     * @param id
     */
    @Override
    public void deleteDataItem(Long id) {
        try {
            // 1.准备Request      // DELETE /item/_doc/{id}
            DeleteRequest request = new DeleteRequest("item", id.toString());
            // 2.发送请求
            restHighLevelClient.delete(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
